import { computed, defineComponent, h, unref, mergeProps, isVNode } from "vue";
import { get, isFunction } from "lodash-es";
export type IFormFieldProps = {
  model: any;
  field?: string | number | [string, string];

  type?: any;
  props?: any;
  renderText?:
    | ((e: any, model: any) => any)
    | string
    | number
    | boolean
    | any[];
  slots?: any;
  tag?: string;
  remote?: any;
};

// 处理静态内容渲染函数
const compileTextFn = (target: any, field: any = "") =>
  isFunction(target) ? target : (data: object) => target ?? get(data, field);

export default defineComponent(
  (props: IFormFieldProps) => {
    const { type, slots, field, props: atomProps, renderText } = props;

    // 特殊：时间范围选择，要单独做处理
    const isRange = Array.isArray(field);

    // 获取value
    const value = computed(() =>
      isRange
        ? [get(props.model, field[0]), get(props.model, field[1])]
        : field && get(props.model, field)
    );

    // 处理update:modelValue更新值
    function handleUpdateModelValue(value: any) {
      if (!field) return;

      if (isRange) {
        const [startVal, endVal] = value || [];
        props.model[field[0]] = startVal;
        props.model[field[1]] = endVal;
      } else {
        props.model[field] = value;
      }
    }

    // 静态内容渲染函数
    const compileText = compileTextFn(renderText, field);

    return () => {
      const cNode = isVNode(type)
        ? type
        : h(type || "span", null, compileText(props.model));

      const node = h(
        cNode,
        mergeProps(
          atomProps,

          (type && {
            modelValue: unref(value),
            "onUpdate:modelValue": handleUpdateModelValue,
          }) ||
            {}
        ),
        slots || cNode.children
      );

      return node;
    };
  },
  {
    props: ["type", "field", "model", "renderText", "slots", "props", "remote"],
  }
);
